package com.example.dingdingtools

import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.util.Log
import com.example.tools.TimeUtils
import com.example.tools.Utils
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 通过无障碍去定时执行打开钉钉，去实现模拟点击并且关闭钉钉
 */
class MyServic : Service() {
    var isOpen = false;
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        onStartTime()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        super.onDestroy()
    }


    private fun onStartTime() {
        GlobalScope.launch {
            while (true) {
                delay(1000)
                if ("08:40:40".contains(TimeUtils.getTimeStampAtTheEndOfDay()) ||
                    "08:42:00".contains(TimeUtils.getTimeStampAtTheEndOfDay()) ||
                    "08:43:30".contains(TimeUtils.getTimeStampAtTheEndOfDay()) ||
                    "08:44:30".contains(TimeUtils.getTimeStampAtTheEndOfDay()) ||
                    "08:45:30".contains(TimeUtils.getTimeStampAtTheEndOfDay())
                ) {
                    Utils.openOtherApp(application, Utils.DDpkg)
                    openActivity()
                    isOpen = true
                }
                Log.e("TAG", "onResume" + TimeUtils.getTimeStampAtTheEndOfDay())
            }
        }
    }

    fun openActivity() {
        GlobalScope.launch {
            if (isOpen) {
                delay(10000)
                Utils.openOtherApp(application, "com.example.dingdingtools")
            }
            cancel()
        }
    }
}